package com.sctvcloud.renhe.ui.activities;

import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.videotracker.entity.VideoInfo;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.ShareFragment;
import com.ruihang.generalibrary.ui.util.ViewUtils;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.GroupOrderHelper;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.NetModeUtil;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.renhe.R;
import com.sctvcloud.renhe.application.Constances;
import com.sctvcloud.renhe.base.BaseActivity;
import com.sctvcloud.renhe.base.BaseCanPlayActivity;
import com.sctvcloud.renhe.beans.FProgram;
import com.sctvcloud.renhe.http.AbsListNetCallback;
import com.sctvcloud.renhe.http.NetUtils;
import com.sctvcloud.renhe.ui.adapter.LookBackAdapter;
import com.sctvcloud.renhe.ui.dialog.TimePopupDialog;
import com.sctvcloud.renhe.ui.utils.GSFPlayerScreenControllImp;
import com.sctvcloud.renhe.ui.utils.GlideUtil;
import com.sctvcloud.renhe.ui.utils.LivingTopControllerImp;
import com.sctvcloud.renhe.ui.utils.TitleUtils;
import com.sctvcloud.renhe.ui.widget.BasePlayerView;
import com.sctvcloud.renhe.utils.ListTypeUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 回看页
 */
public class RenheActivity extends BaseCanPlayActivity implements LookBackAdapter.ChoiceDateCallBack, TimePopupDialog.PopItemClick,
        CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener,
        ExpandableListView.OnGroupClickListener, ExpandableListView.OnChildClickListener, CanRefreshLayout.IScrollView {
    @BindView(R.id.title_top_layout)
    protected ViewGroup title_lay;
    @BindView(R.id.look_back_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.look_back_player)
    protected BasePlayerView playerView;
    @BindView(R.id.look_back_list)
    protected ExpandableListView look_back_list;
    @BindView(R.id.video_container)
    protected AbsoluteLayout videoContainer;
    @BindView(R.id.can_content_view)
    protected CustomLinearLayout detail;

    @BindView(R.id.title_top_logo_layout)
    protected LinearLayout title_top_logo_layout;
    @BindView(R.id.title_top_title)
    protected CustomFontTextView title_top_title;

    private ImageView thumb;

    private LookBackAdapter lookbackAdapter;
    private TimePopupDialog timePopupDialog;
    public static final String TIME_TAG = "dia_time_choice";
    private int currentPage = 0;
    private int pageAll = 0;
    private List<FProgram> programList;
    private GroupOrderHelper groupOrderHelper;
    private String playBackUrl;
    private FProgram program;
    private GSFPlayerScreenControllImp screenControllImp;
    private LivingTopControllerImp topControllerImp;
    private Handler handler;
    private String title;
    private String programUrl;
    private String pageUrl;
    private int dateCurrentPos;

    private boolean isFirst = true;

    private boolean hasInitedPlayer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_renhe);
        ButterKnife.bind(this);
    }

    @Override
    protected void initVideoPlayer(@NonNull BasePlayerView player, VideoInfo info, boolean isLiving) {
        if (!hasInitedPlayer) {
            super.initVideoPlayer(player, info, false);
            thumb = playerView.getThumbImge();
//            thumb.setScaleType(ImageView.ScaleType.FIT_XY);
            thumb.setImageResource(R.mipmap.icon_def_16_9_l);
//            playerView.setThumbImageView(thumb);
        }
    }

    @Override
    protected StandardGSYVideoPlayer getVideoPlayer() {
        return playerView;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (playerView != null) {
            playerView.onConfigurationChanged(this, newConfig, orientationUtils);
        }
    }

    @Override
    public void onNetPromptCallBacked(boolean isContinue) {
        super.onNetPromptCallBacked(isContinue);
        if (isContinue) {
            playerView.startPlayLogic();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (playerView != null) {
            playerView.onVideoPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (playerView != null) {
            playerView.onVideoResume();
        }
    }

    private void initView() {

        title_top_logo_layout.setVisibility(View.GONE);
        title_top_title.setVisibility(View.VISIBLE);
        title_top_title.setText(getText(R.string.text_news));

        look_back_list.setGroupIndicator(null);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        look_back_list.setOnGroupClickListener(this);
        look_back_list.setOnChildClickListener(this);
        ViewUtils.resetTo169Size(playerView);
        groupOrderHelper = new GroupOrderHelper();
        playBackUrl = getIntent().getStringExtra(BaseActivity.EX_URL);
        handler = new Handler();
        refreshLayout.autoRefresh();
        detail.setiScrollView(this);
    }

    @OnClick(value = {R.id.title_top_layout_back, R.id.title_top_layout_edit})
    public void topClick(View view) {
        switch (view.getId()) {
            case R.id.title_top_layout_back:
                finish();
                break;
            case R.id.title_top_layout_edit:
                if (program != null && !TextUtils.isEmpty(program.getSharedUrl())) {
                    this.setNewsId(program.getProgrammeId());
                    showShareFragment(program, new ShareFragment.OnShareFragmentClickListener() {
                        @Override
                        public void onClick(Pair<String, String> pairs) {

                        }
                    });
                } else {
                    toast(R.string.share_data_wrong);
                }
                break;
//            case R.id.look_back_play:
//                if (program != null) {
//                    playVideo(program);
//                }
//                break;
        }
    }

    private synchronized void playVideo(FProgram pro, boolean playNow) {
        JLog.e("ssas " + pro);
        if (TextUtils.isEmpty(pro.getProgrammeUrl())) {
            toast("数据错误");
            return;
        }
        int netType = NetModeUtil.GetNetype(this);
        contentVideoUrl = UrlUtils.linkUrls(Constances.ST_BASE_URL, program.getProgrammeUrl());
        //contentVideoUrl = "http://baobab.wdjcdn.com/1457978787439_5544_854x480.mp4";
//        if (initFloatVideoUtils(lookBack_img, videoContainer, 0)) {
//
//        }
        playerView.setUp(contentVideoUrl, false, pro.getDataTitle());
        if (playNow) {
//            if (isShouldMuteStart()) {
//                playerView.setMute(true);
//            }
            playerView.startPlay();
        } else {
            playerView.setTitleStr(pro.getProgrammeTitle());
        }
        isFirst = false;
    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public void onRefresh() {
        currentPage = 0;
        getLookbackProList();
    }

    @Override
    protected void onDestroy() {
        if (floatVideoUtils != null) {
            floatVideoUtils.onDestory();
        }
        if (playerView != null) {
            playerView.release();
        }
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (StandardGSYVideoPlayer.backFromWindowFull(this)) {
            actionToPortrait();
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void getDateCallBack(int position, String url) {
        dateCurrentPos = position;
        if (!TextUtils.isEmpty(url) && url.length() - 24 > 0) {
            pageUrl = url.substring(0, url.length() - 24);
            showDateDialog();
        } else {
            toast("暂无数据");
        }
    }

    public void getItemClick(int groupPosition, int childPosition) {
        program = (FProgram) lookbackAdapter.getChild(groupPosition, childPosition);
        if (program != null) {
            GlideUtil.loadImgLarge169Def(this, program.getProgrammeImage(), thumb);
            playVideo(program, true);
        }

    }

    private void showDateDialog() {
        if (timePopupDialog == null) {
            timePopupDialog = new TimePopupDialog().setPopItemClick(this);
        }
        safeShowDialog(timePopupDialog, TIME_TAG);
    }

    @Override
    public void selectTime(String year, String month, String day) {
        if (month.length() == 1) {
            month = "0" + month;
        }
        if (day.length() == 1) {
            day = "0" + day;
        }
        String dateStr = year + month + day;
        int dateInt = Integer.parseInt(dateStr);
        if (dateInt < 20180331) {
            programUrl = pageUrl + year + month + day + ".json";
        } else {
            programUrl = pageUrl + year + "/" + month + "/" + day + "/" + year + month + day + ".json";
        }
//        programUrl = pageUrl + year + "/" + month + "/" + day + "/" + year + month + day + ".json";
        // programUrl="/sctv/lookback/2/20170715.json";
        getProList(programUrl, dateCurrentPos);
    }

    private synchronized void onNetFinish() {
        if (groupOrderHelper.removeOne()) {
            refreshLayout.refreshComplete();
        }
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
    }

    private void getLookbackProList() {
        if (TextUtils.isEmpty(playBackUrl)) {
            toast("数据错误");
            return;
        }
        groupOrderHelper.addOne();
        NetUtils.getNetAdapter().getProgramList(getOwnerName(), playBackUrl, currentPage, new AbsListNetCallback<FProgram>(ListTypeUtils.FProgram()) {
            @Override
            public void onSuc(List<FProgram> fPrograms) {
                if (ListUtils.isListValued(fPrograms)) {
                    programList = fPrograms;
                    setProgramData(programList);
                }

            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }
        });
    }

    private void setProgramData(List<FProgram> programData) {
        VideoInfo videoInfo = new VideoInfo("");
        initVideoPlayer(playerView, videoInfo, false);
        for (int i = 0; i < programData.size(); i++) {
            groupOrderHelper.addOne();
            FProgram program = programData.get(i);
            String programmeUrl = program.getProgrammeUrl();
            if (!TextUtils.isEmpty(programmeUrl)) {
                getProList(programmeUrl, i);

            } else {
                JLog.e("==error==" + "url错误");
            }
        }

    }

    private void getProList(final String programmeUrl, final int i) {

        groupOrderHelper.addOne();
        NetUtils.getNetAdapter().getProgramArray(getOwnerName(), programmeUrl, new AbsListNetCallback<FProgram>(ListTypeUtils.FProgram()) {
            @Override
            public void onSuc(List<FProgram> fPrograms) {
                setProList(fPrograms, getInt1());
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                setProList(null, getInt1());
                //toast(R.string.look_back_no_data);

            }

            @Override
            public void onEnd() {
                super.onEnd();
//                onNetFinish();
            }
        }.setInt1(i));
    }

    private void setProList(final List<FProgram> fPrograms, int i) {
        if (ListUtils.isListValued(fPrograms)) {
            programList.get(i).setProgrammeList(fPrograms);
            if (i == 0) {
                if (program == null) {
                    program = fPrograms.get(0);
                    if (thumb != null) {
                        GlideUtil.loadImgLarge169Def(this, program.getProgrammeImage(), thumb);
                        playVideo(program, false);
                        program.setSelect(true);
                    }
                }
            }
        } else {
            programList.get(i).setProgrammeList(null);
        }
        if (currentPage == 0) {
            if (lookbackAdapter == null) {
                lookbackAdapter = new LookBackAdapter(programList, this).setChoiceDateCallBack(this);
                look_back_list.setAdapter(lookbackAdapter);
                if (programList.size() > 1) {
                    look_back_list.expandGroup(0);
                }
            } else {
                lookbackAdapter.setData(programList);
            }
        }
    }

    @Override
    public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
//        if (ListUtils.isListValued(programList.get(groupPosition).getProgrammeList())) {
//            return false;
//        } else {
//            return true;
//        }
        return false;
    }

    @Override
    protected void onChangedToLandscape(Configuration newConfig) {
        super.onChangedToLandscape(newConfig);
        if (title_lay != null) {
            title_lay.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onChangedToPortrait(Configuration newConfig) {
        super.onChangedToPortrait(newConfig);
        if (title_lay != null) {
            title_lay.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected boolean isShouldMuteStart() {
        return isFirst;
    }

    private void setTitleDelayed() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (topControllerImp != null) {
                    topControllerImp.setTitle(program.getProgrammeTitle());
                }
            }
        }, 800);
    }

    @Override
    public boolean canScrollUp(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(look_back_list, -1);
    }

    @Override
    public boolean canScrollDown(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(look_back_list, 1);
    }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {

        for (int i = 0; i < programList.size(); i++) {
            List<FProgram> list = programList.get(i).getProgrammeList();
            if (!ListUtils.isListValued(list)) {
                continue;
            }
            for (int j = 0; j < list.size(); j++) {
                if (i == groupPosition && j == childPosition) {
                    list.get(j).setSelect(true);
                } else {
                    list.get(j).setSelect(false);
                }
            }
        }
        lookbackAdapter.notifyDataSetChanged();
        getItemClick(groupPosition, childPosition);
        return true;
    }
}